package com.wujian.love.study.designpattern;

import org.springframework.util.ResourceUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * @ClassName: ReadXML1
 * @Description:
 * @Author: wuj
 * @Date: 2021-01-11 09:33
 **/
class ReadXML1 {


    public static final String XML_PATH = "classpath:config1.xml";
    //该方法用于从XML配置文件中提取具体类类名，并返回一个实例对象
    public static Object getObject() {
        try {
            //创建文档对象
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            //获取文件的相对路径  可在控制台打印查看输出结果
            File file =  ResourceUtils.getFile(XML_PATH);
            String filePath = ResourceUtils.getFile(XML_PATH).getPath();
            System.out.println("文件的路径"+filePath);
            doc = builder.parse(file);
            //获取包含类名的文本节点
            NodeList nl = doc.getElementsByTagName("className");
            Node classNode = nl.item(0).getFirstChild();
            String cName = "com.wujian.love.study.designpattern." + classNode.getNodeValue();
            System.out.println("新类名："+cName);
            //通过类名生成实例对象并将其返回
            Class<?> c = Class.forName(cName);
            Object obj = c.newInstance();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
